package org.cheetah.core;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

import org.cheetah.core.action.Action;
import org.cheetah.core.action.ActionPipeline;
import org.cheetah.core.action.impl.DefaultActionPipeline;
import org.cheetah.core.exchange.Exchange;
import org.cheetah.core.impl.DefaultServiceInvoker;

public class Service {
	private final static ConcurrentHashMap<String, Service> services = new ConcurrentHashMap<String, Service>();

	public static ServiceInvoker invoker(String name) {
		Service svc = services.get(name);
		if (svc == null) {
			return null;
		}

		return new DefaultServiceInvoker(svc);
	}

	public static void register(String name, Service service) {
		if (services.putIfAbsent(name, service) != null) {
			throw new IllegalArgumentException("service " + name
					+ " already exists");
		}
	}

	public static Service find(String name) {
		return services.get(name);
	}

	public static void remove(String name) {
		services.remove(name);
	}

	public static void clear() {
		services.clear();
	}

	private String name;

	private ActionPipeline pipeline;

	public Service(String name) {
		this.name = name;
		this.pipeline = null;
	}

	public void setPipeline(Collection<? extends Action> actions) {
		pipeline = new DefaultActionPipeline(actions);
	}

	public String getName() {
		return name;
	}

	public void process(Exchange exchange) throws Exception {
		pipeline.process(exchange);
	}
}
